package com.lancoo.znbkxx.teacher.ui.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.klgcourseware.manager.KlgCourseWareManager
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.Ext.Companion.GLOBAL_GRADE
import com.lancoo.znbkxx.teacher.Ext.Companion.OBSINFO
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.*
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtPublishNewBinding
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.Classical
import com.lancoo.znbkxx.teacher.model.data.ImportKlg
import com.lancoo.znbkxx.teacher.ui.activity.CommentDetailActivity
import com.lancoo.znbkxx.teacher.ui.activity.VideoPlayerActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.GlideEngine
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia

import kotlinx.android.synthetic.main.fmt_publish_new.*
import org.json.JSONArray

/**
 * @author : Admin
 * @date   : 2019/8/13 15:38
 * @desc   :
 */
class PublishFragment : BaseVMFragment<HardSolutionViewModel, FmtPublishNewBinding>(),
        View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener, ClassicalFragment.OnClickClassicalListener {
    private var isCamera: Boolean = true
    private lateinit var cameraMenu: PopupWindow
    private lateinit var adapter: GridMediaAdapter
    private lateinit var classicalAdapter: ClassicalAdapter
    private lateinit var zsdAdapter: ZsdListShowAdapter
    private val navigationHeight by lazy {
        resources.getDimensionPixelSize(
                resources.getIdentifier("navigation_bar_height", "dimen", "android"))
    }
    private var classicalNum: Int = 0
    private val classicalInfoList = mutableListOf<Classical>()
    private val classicalList = mutableListOf<Classical>()
    private var classicalTempList = mutableListOf<Classical>()
    private var selectList = mutableListOf<LocalMedia>()
    private var zsdList = mutableListOf<ImportKlg>()
    private var tempList = mutableListOf<LocalMedia>()
    private val audioList = arrayListOf<LocalMedia>()
    private var tempAudioList = arrayListOf<LocalMedia>()
    private val GET_PERMISSION_REQUEST = 100 //权限申请自定义码
    private val paperName by lazy { arguments?.getString("paperName") }
    private lateinit var content: String
    private val audioPath by lazy { viewModel.hardSolution.value?.AudioPath }
    private val imagePath by lazy { viewModel.hardSolution.value?.ImagePath }
    private val videoPath by lazy { viewModel.hardSolution.value?.VideoPath }
    private var state: Int = -1
    private lateinit var dialog: LoadingDailog
    private val saveState by lazy { viewModel.hardSolution.value!!.State }
    private val typeNo by lazy { viewModel.hardSolution.value!!.TkModel.TypeNo }
    private val quesID by lazy { viewModel.hardSolution.value!!.TkModel.QuesID }
    private var position = -1
    private val zsdPopupWindow by lazy {
        KnowledgePointWindow(requireContext(), this,
                if (viewModel.hardSolution.value!!.ZSDList.isNotEmpty()) viewModel.hardSolution.value!!.ZSDList.sortedBy { it.Name.length } else viewModel.hardSolution.value!!.TkModel.ImportKlgList.sortedBy { it.Name.length }).apply {
            setOnDismissListener { dismissPopupWindow() }
        }
    }

    //    private var hasVideo: Boolean = false
    lateinit var video: LocalMedia

    companion object {
        private const val PAPERNAME = "paperName"
        fun newInstance(paperName: String): PublishFragment {
            val fragment = PublishFragment()
            val bundle = Bundle()
            bundle.putString(PAPERNAME, paperName)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_publish_new
    }

    override fun initView() {
        initEditText()
        initPopWindow()
        initClassical()
        initRecyclerView()
        initZsdList()
        Handler().post {
            (activity as CommentDetailActivity).loadingDialog.dismiss()
        }
    }

    private fun initClassical() {
        val manager = GridLayoutManager(activity, 3)
        binding.rvClassical.layoutManager = manager
        binding.rvClassical.addItemDecoration(
                EvenItemDecoration(DensityUtils.dp2px(activity, 10f), 3))
        classicalAdapter = ClassicalAdapter(R.layout.item_classical, classicalList)
        classicalAdapter.onItemClickListener = this
        classicalAdapter.onItemChildClickListener = this
        binding.rvClassical.adapter = classicalAdapter
        when (typeNo) {
            "Q", "V", "X", "W", "G", "b", "d", "g", "k", "f" -> {
                if (viewModel.hardSolution.value?.ClassicalList.isNullOrEmpty()) {
//                    if (saveState == 1) {
//                        binding.llClassic.visibility = View.GONE
//                        binding.rvClassical.visibility = View.GONE
//                    }
                } else {
                    binding.llClassic.visibility = View.VISIBLE
                    binding.rvClassical.visibility = View.VISIBLE
                    classicalList.addAll(viewModel.hardSolution.value?.ClassicalList!!)
                    classicalNum = classicalList.size
                    classicalTempList.addAll(classicalList)
//                    if (saveState == 1) {
//                        classicalAdapter.updateState(1)
//                    }
                }
            }
            else -> {
                binding.llClassic.visibility = View.GONE
                binding.rvClassical.visibility = View.GONE
            }
        }
    }

    private fun initEditText() {
        content = viewModel.hardSolution.value?.SolutionContent!!
        binding.edtContent.setText(content)
//        if (saveState == 1) {
//            binding.cv.setCardBackgroundColor(Color.parseColor("#43cbea"))
//            if (content.isBlank()) {
//                binding.edtContent.setText("暂无讲评")
//            }
//            binding.edtContent.setTextColor(Color.WHITE)
//            binding.edtContent.isFocusable = false
//            binding.edtContent.isClickable = false
//        }
    }

    @SuppressLint("SetTextI18n")
    private fun initRecyclerView() {
        binding.tvToHardsolution.setOnClickListener(this)
        binding.rv.isFocusableInTouchMode = false
        val manager = GridLayoutManager(activity, 3)
        binding.rv.layoutManager = manager
        binding.rv.addItemDecoration(EvenItemDecoration(DensityUtils.dp2px(activity, 10f), 3))
        adapter = GridMediaAdapter(R.layout.item_preview, selectList, viewModel.videoMap.value)
        adapter.onItemClickListener = this
        adapter.onItemChildClickListener = this
        binding.rv.adapter = adapter
        if (audioPath!!.isBlank() && imagePath!!.isBlank() && videoPath!!.isBlank()) {
//            if (saveState == 1) {
//                binding.view13.visibility = View.GONE
//                binding.textView16.visibility = View.GONE
//                binding.rv.visibility = View.GONE
//            }
        } else {
            if (audioPath!!.isNotBlank()) {
                val recordList = audioPath!!.split("|")
                tv_to_hardsolution.text = "继续讲评(${recordList.size})"
                for (i in recordList.indices) {
                    val path = recordList[i]
                    val media = LocalMedia()
//                    val path = item.getString("src")
                    //                    media.key = path
                    media.path = OBSINFO?.ServerWithBucket + path
                    media.mimeType = "audio/" + path.substring(path.lastIndexOf(".") + 1)
                    //                    media.mimeType = 3
                    audioList.add(media)
                }
            }
            if (!imagePath!!.isBlank() && !imagePath!!.contains("{}")) {
                val imgList = JSONArray(imagePath)
                for (i in 0 until imgList.length()) {
                    val item = imgList.getJSONObject(i)
                    val media = LocalMedia()
                    val path = item.getString("src")
                    //                    media.key = path
                    media.path = OBSINFO?.ServerWithBucket + path
                    media.mimeType = "image/" + path.substring(path.lastIndexOf(".") + 1)
                    //                    media.mimeType = 1
                    selectList.add(media)
                }
            }
            if (!videoPath!!.isBlank()) {
                //                hasVideo = true
//                val videoList: JSONArray
//                val item: JSONObject
//                if (videoPath!!.contains("src")) {
//                    videoList = JSONArray(videoPath)
//                    item = videoList.getJSONObject(0)
//                    path = item.getString("src")
//                } else {
                val path = videoPath!!
//                }
                video = LocalMedia()
                video.path = OBSINFO?.ServerWithBucket + path
                video.mimeType = "video/" + path.substring(path.lastIndexOf(".") + 1)
                selectList.add(video)
                viewModel.saveVideoInfo(video.path)
            }
            tempList.addAll(selectList)
            tempAudioList.addAll(audioList)
//            if (saveState == 1) {
//                adapter.updateState(1)
//            }
        }
    }

    private fun initZsdList() {
        zsdList.addAll(viewModel.hardSolution.value!!.ZSDList.sortedBy { it.Name.length })
        zsdAdapter = ZsdListShowAdapter(zsdList)
        zsdAdapter.onItemClickListener = this
        val manager = FlexboxLayoutManager(requireContext(), FlexDirection.ROW,
                FlexWrap.WRAP).apply {
            alignItems = AlignItems.FLEX_START
        }
        binding.rvZsd.layoutManager = manager
        val hashMap = hashMapOf<String, Int>()
        hashMap[SpacesItemDecoration.TOP_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        hashMap[SpacesItemDecoration.BOTTOM_SPACE] = DensityUtils.dp2px(requireContext(), 5f)
        hashMap[SpacesItemDecoration.LEFT_SPACE] = DensityUtils.dp2px(requireContext(), 10f)
        binding.rvZsd.addItemDecoration(SpacesItemDecoration(hashMap))
        binding.rvZsd.adapter = zsdAdapter
        iv_zsd_add.setOnClickListener(this)
    }

    private fun initPopWindow() {
        val mPopView = layoutInflater.inflate(R.layout.view_note_edit, null)
        val tvCancel = mPopView.findViewById<TextView>(R.id.tv_cancel)
        val tvPhotograph = mPopView.findViewById<TextView>(R.id.tv_photograph)
        val tvFromAlbum = mPopView.findViewById<TextView>(R.id.tv_fromAlbum)
        //        val tvVideo = mPopView.findViewById<TextView>(R.id.tv_video)
        tvCancel.setOnClickListener(this)
        tvPhotograph.setOnClickListener(this)
        tvFromAlbum.setOnClickListener(this)
        //        tvVideo.setOnClickListener(this)
        cameraMenu = PopupWindow(mPopView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT)
        cameraMenu.isOutsideTouchable = true
        //获取焦点
        cameraMenu.isFocusable = true
        cameraMenu.animationStyle = R.style.PopupWindow
        cameraMenu.setOnDismissListener { dismissPopupWindow() }
    }

    /*显示弹窗*/
    private fun showPopWindow() {
        val lp = requireActivity().window.attributes
        lp.alpha = 0.4f
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        requireActivity().window.attributes = lp
    }

    private fun dismissPopupWindow() {
        val lp = requireActivity().window.attributes
        lp.alpha = 1f
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        requireActivity().window.attributes = lp
    }

    /*保存或发布*/
    fun upLoad(state: Int, oneOnOne: Boolean) {
        if (isBlank()) {
            MyToast.showToast( "未制作任何内容，请勿发布")
            return
        }
        this.state = state
        val message = if (state == 0) "保存中..." else "发布中..."
        dialog = LoadingDailog.Builder(activity).setMessage(message).setCancelOutside(false)
                .setCancelable(false).create()
        dialog.show()
        if (oneOnOne) {
            viewModel.upLoadOneOnOne(zsdPopupWindow.zsdList.toMutableList(), classicalList,
                    selectList.plus(audioList).toMutableList(),
                    tempList.plus(tempAudioList).toMutableList(),
                    binding.edtContent.text.toString(),
                    paperName!!, state)
        } else {
            viewModel.upLoad(zsdPopupWindow.zsdList.toMutableList(), classicalList,
                    selectList.plus(audioList).toMutableList(),
                    tempList.plus(tempAudioList).toMutableList(),
                    binding.edtContent.text.toString(),
                    paperName!!, state)
        }
    }

    /*是否为空*/
    fun isBlank(): Boolean {
        return binding.edtContent.text.isEmpty() && selectList.isEmpty() && classicalList.isEmpty() && audioList.isEmpty()
    }

    /*是否相等*/
    fun areTheSame(): Boolean {
        return content == binding.edtContent.text.toString() && tempList == selectList && classicalList == classicalTempList && tempAudioList == audioList
    }

    override fun startObserve() {
        viewModel.resultInfo.observe(this, Observer {
            dialog.dismiss()
            if (it.result == 1) {
                if (state == 0) {
                    content = binding.edtContent.text.toString()
                    tempList = selectList
                    tempAudioList = audioList
                    classicalTempList = classicalList
                    MyToast.showToast("保存成功")
                    OperationHelp.operationLog(5, activity)
                } else if (state == 1) {
//                    if (binding.edtContent.text.isNullOrBlank()) {
//                        binding.edtContent.setText("暂无讲评")
//                    }
//                    binding.cv.setCardBackgroundColor(Color.parseColor("#43cbea"))
//                    binding.edtContent.setTextColor(Color.WHITE)
//                    binding.edtContent.isFocusable = false
//                    binding.edtContent.isClickable = false
//                    adapter.updateState(1)
//                    classicalAdapter.updateState(1)
                    (parentFragment as CommentDetailFragment).apply {
                        btnPublish.text = "重新发布"
                        btnSave.visibility = View.GONE
                    }
                    content = binding.edtContent.text.toString()
                    tempList = selectList
                    tempAudioList = audioList
                    classicalTempList = classicalList
//                    if (selectList.isEmpty()) {
//                        binding.view13.visibility = View.GONE
//                        binding.textView16.visibility = View.GONE
//                    }
                    OperationHelp.operationLog(6, activity)
                    MyToast.showToast("发布成功")
                }
            } else {
                if (state == 0) {
                    MyToast.showToast( "保存失败")
                } else if (state == 1) {
                    MyToast.showToast( "发布失败")
                }
            }
        })
        viewModel.success.observe(this, Observer {
            dialog.dismiss()
            if (it == 1) {
                if (state == 0) {
                    content = binding.edtContent.text.toString()
                    tempList = selectList
                    tempAudioList = audioList
                    classicalTempList = classicalList
                    MyToast.showToast("保存成功")
                    OperationHelp.operationLog(5, activity)
                } else if (state == 1) {
//                    if (binding.edtContent.text.isNullOrBlank()) {
//                        binding.edtContent.setText("暂无讲评")
//                    }
//                    binding.cv.setCardBackgroundColor(Color.parseColor("#43cbea"))
//                    binding.edtContent.setTextColor(Color.WHITE)
//                    binding.edtContent.isFocusable = false
//                    binding.edtContent.isClickable = false
//                    adapter.updateState(1)
//                    classicalAdapter.updateState(1)
                    (parentFragment as CommentDetailFragment).apply {
                        btnPublish.text = "重新发布"
                        btnSave.visibility = View.GONE
                    }
                    content = binding.edtContent.text.toString()
                    tempList = selectList
                    tempAudioList = audioList
                    classicalTempList = classicalList
//                    if (selectList.isEmpty()) {
//                        binding.view13.visibility = View.GONE
//                        binding.textView16.visibility = View.GONE
//                    }
                    OperationHelp.operationLog(6, activity)
                    MyToast.showToast( "发布成功")
                }
            } else {
                if (state == 0) {
                    MyToast.showToast( "保存失败")
                } else if (state == 1) {
                    MyToast.showToast( "发布失败")
                }
            }
        })
        viewModel.mErrorMsg.observe(this, Observer {
            dialog.dismiss()
            MyToast.showToast(it)
        })
        viewModel.mediaList.observe(this, Observer {
            adapter.setNewData(it)
        })
        viewModel.classicalList.observe(this, Observer {
            if (it.size == 0) {
                MyToast.showToast("当前无经典案例")
                return@Observer
            }
            classicalInfoList.clear()
            classicalInfoList.addAll(it)
            val classicalDialog = ClassicalDialog(classicalInfoList, this, this)
            if (classicalAdapter.getItemViewType(position) == ClassicalAdapter.TYPE_ADD) {
                classicalDialog.show(parentFragmentManager, "add")
            } else {
                classicalDialog.show(parentFragmentManager, "preview")
            }
        })
        viewModel.videoMap.observe(this, Observer {
            adapter.updateMap(it)
        })
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_close -> zsdPopupWindow.dismiss()
            R.id.tv_confirm -> {
                zsdPopupWindow.dismiss()
                zsdAdapter.setNewData(zsdPopupWindow.zsdList.sortedBy { it.Name.length })
                zsdAdapter.notifyDataSetChanged()
            }
            R.id.iv_zsd_add -> {
                zsdPopupWindow.showAtLocation(binding.cv, Gravity.BOTTOM, 0, 0)
                showPopWindow()
            }
            R.id.tv_cancel -> cameraMenu.dismiss()
            R.id.tv_photograph -> {
                isCamera = true
                cameraMenu.dismiss()
                if (checkCameraPermission()) {
                    PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                            .isCompress(true).selectionData(selectList)
                            .forResult(PictureConfig.CHOOSE_REQUEST)
                } else {
                    //不具有获取权限，需要进行权限申请
                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA),
                            GET_PERMISSION_REQUEST)
                }
            }
            R.id.tv_fromAlbum -> {
                isCamera = false
                cameraMenu.dismiss()
                if (checkCameraPermission()) {
                    PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                            .imageEngine(GlideEngine.createGlideEngine()).maxSelectNum(5)
                            .isCamera(false).isCompress(true).videoMinSecond(4)
                            .selectionData(selectList.apply {
                                if (this@PublishFragment::video.isInitialized) {
                                    remove(video)
                                }
                            }).forResult(PictureConfig.CHOOSE_REQUEST)
                } else {
                    //不具有获取权限，需要进行权限申请
                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA),
                            GET_PERMISSION_REQUEST)
                }
            }
            R.id.tv_to_hardsolution -> if (checkCameraPermission()) {
                (parentFragment as CommentDetailFragment).switchToRecording()
            } else {
                requestPermissions(
                        arrayOf(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.RECORD_AUDIO,
                                Manifest.permission.CAMERA
                        ), GET_PERMISSION_REQUEST
                )
            }
            //            R.id.tv_video -> {
            //                cameraMenu.dismiss()
            //                if (checkCameraPermission()) {
            //                    PictureSelector.create(this).openCamera(PictureMimeType.ofVideo()).compress(false).videoQuality(0).videoMinSecond(4).selectionMedia(selectList).forResult(PictureConfig.CHOOSE_REQUEST)
            //                } else {
            //                    //不具有获取权限，需要进行权限申请
            //                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA), GET_PERMISSION_REQUEST)
            //                }
            //            }
        }
    }

    /*保存录音讲评*/
    fun saveAudio(type: Int, media: LocalMedia) {
        if (type == 1) {
            audioList.add(media)
        } else {
            audioList.remove(media)
        }
    }

    /*获取录音*/
    fun getAudioList(): ArrayList<LocalMedia> {
        return audioList
    }

    /*权限检查*/
    private fun checkCameraPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (adapter) {
            is GridMediaAdapter -> if (position == selectList.size) {
                cameraMenu.showAtLocation(binding.cv, Gravity.BOTTOM, 0, navigationHeight)
                showPopWindow()
            } else {
                val media = selectList[position]
                val pictureType = media.mimeType
                when {
                    pictureType.contains("image") ->
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(this).themeStyle(R.style.picture_default_style)
                                .imageEngine(GlideEngine.createGlideEngine())
                                .openExternalPreview(position, selectList)
                    pictureType.contains("video") -> {
                        // 预览视频
                        //                        PictureSelector.create(this).externalPictureVideo(media.path)
                        val videoPath =
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) media.androidQToPath else media.path
                        val intent = Intent(activity, VideoPlayerActivity::class.java).putExtra(
                                "VideoPath", videoPath ?: media.path)
                        startActivity(intent)
                    }
                    pictureType.contains("audio") ->
                        // 预览音频
                        PictureSelector.create(this).externalPictureAudio(media.path)
                }
            }
            is ZsdListShowAdapter -> {
                var code = ""
                viewModel.hardSolution.value!!.TkModel.ImportKlgList.forEach {
                    if (adapter.data[position].UniqueCode == it.UniqueCode) {
                        code = it.Code
                    }
                }
                KlgCourseWareManager.getInstance()
                        .launchCourseWareKlg(requireContext(), code, Ext.KNOWLEDGEPOINT_URL,
                                Ext.CoursewareOBSInfo!!.ServerWithBucket + Ext.CoursewareOBSInfo!!.SysOBSRelativePath,
                                false, when (GLOBAL_GRADE) {
                            "K6", "K7", "K8", "K9" -> "B"
                            else -> "C"
                        })
            }
            is ClassicalAdapter -> if (adapter.getItemViewType(
                            position) == ClassicalAdapter.TYPE_ADD) {
                if (classicalNum >= 3) {
                    MyToast.showToast("最多只能选择3份经典案例")
                    return
                }
                this.position = position
                viewModel.getClassicalList(CurrentUser.getToken(), CurrentUser.getSchoolID(), quesID,
                        when (GLOBAL_GRADE) {
                            "K6", "K7", "K8", "K9" -> "B"
                            else -> "C"
                        }, classicalList, CurrentUser.UserID)
            } else {
                this.position = position
                val list = mutableListOf<Classical>()
                list.add(classicalList[position])
                viewModel.getSelectedClassicalList(CurrentUser.getToken(), CurrentUser.getSchoolID(), quesID,
                        when (GLOBAL_GRADE) {
                            "K6", "K7", "K8", "K9" -> "B"
                            else -> "C"
                        }, list, CurrentUser.getUserID())
            }
        }
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {
            R.id.iv_delete -> when (adapter) {
                is GridMediaAdapter -> {
                    selectList.removeAt(position)
                    adapter.notifyItemRemoved(position)
                    adapter.notifyItemRangeChanged(position, selectList.size)
                }
                is ClassicalAdapter -> {
                    classicalList.removeAt(position)
                    classicalNum--
                    adapter.notifyItemRemoved(position)
                    adapter.notifyItemRangeChanged(position, classicalList.size)
                }
            }
        }
    }


    override fun onClickClassical(textview: TextView, position: Int) {
        if (textview.tag == "unselected") {
            if (classicalNum >= 3) {
                MyToast.showToast( "最多只能选择3份经典案例")
                return
            }
            classicalNum++
            textview.apply {
                tag = "selected"
                text = "取消选用"
                setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(context,
                        R.mipmap.aibk_icon_select_classical), null, null, null)
            }
            classicalList.add(classicalInfoList[position])
            classicalAdapter.notifyDataSetChanged()

        } else {
            classicalNum--
            textview.apply {
                tag = "unselected"
                text = "选用"
                setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(context,
                        R.mipmap.aibk_icon_unselect_classical), null, null, null)
            }
            classicalList.remove(classicalInfoList[position])
            classicalAdapter.notifyDataSetChanged()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == AppCompatActivity.RESULT_CANCELED) {
            return
        }
        when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> {
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data)
                if (this::video.isInitialized) {
                    selectList.add(video)
                }
                viewModel.mediaList.value = selectList
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == GET_PERMISSION_REQUEST) {
            var size = 0
            if (grantResults.isNotEmpty()) {
                val writeResult = grantResults[0]
                //读写内存权限
                val writeGranted = writeResult == PackageManager.PERMISSION_GRANTED //读写内存权限
                if (!writeGranted) {
                    size++
                }
                //录音权限
                val recordPermissionResult = grantResults[1]
                val recordPermissionGranted =
                        recordPermissionResult == PackageManager.PERMISSION_GRANTED
                if (!recordPermissionGranted) {
                    size++
                }
                //相机权限
                val cameraPermissionResult = grantResults[2]
                val cameraPermissionGranted =
                        cameraPermissionResult == PackageManager.PERMISSION_GRANTED
                if (!cameraPermissionGranted) {
                    size++
                }
                if (size == 0) {
                    if (isCamera) {
                        PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                                .isCompress(true).selectionData(selectList)
                                .forResult(PictureConfig.CHOOSE_REQUEST)
                    } else {
                        PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                                .imageEngine(GlideEngine.createGlideEngine()).maxSelectNum(5)
                                .isCamera(false).isCompress(true).videoMinSecond(4)
                                .selectionData(selectList.apply {
                                    if (this@PublishFragment::video.isInitialized) {
                                        remove(video)
                                    }
                                }).forResult(PictureConfig.CHOOSE_REQUEST)
                    }
                } else {
//                    Toast.makeText(activity, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show()
                    MyToast.showToast("请到设置-权限管理中开启")
                }
            }
        }
    }
}